package tjs.study.notes.mysql.mybatis.srevice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tjs.study.notes.mysql.mybatis.domain.CmdbTempInstanceLevel;
import tjs.study.notes.mysql.mybatis.mapper.CmdbTempInstanceLevelMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by Nicky.Tang on 2022/7/2 下午4:14
 *
 * @since 02.12.10
 */
@Service
public class DoTestService {
    @Autowired
    private CmdbTempInstanceLevelMapper cmdbTempInstanceLevelMapper;
    @Autowired
    private InsertService insertService;

    public void testInsertIgnore(int threadSize) {

        CountDownLatch countDownLatchFinsh = new CountDownLatch(threadSize);
        for (int i = 0; i < threadSize; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    countDownLatchFinsh.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                insertService.doTest(finalI);
            }).start();

            countDownLatchFinsh.countDown();
        }
    }


    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void init(Long size) throws InterruptedException {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        cmdbTempInstanceLevelMapper.truncateAll();
        Thread.currentThread().sleep(2000);
        List<CmdbTempInstanceLevel> res = new ArrayList<>();
        for (Long i = 0l; i < size; i++) {
            for (Long j = 0l; j < 300; j++) {
                res.add(new CmdbTempInstanceLevel(i, j, j));
            }
            if (i % 50 == 0) {
                cmdbTempInstanceLevelMapper.insertBatch(res);
                res = new ArrayList<>();
            }
        }
        if (!CollectionUtils.isEmpty(res)) {
            cmdbTempInstanceLevelMapper.insertBatch(res);
        }
    }
}
